//
//  RefreshIconLayer.m
//  Refresh
//
//  Created by ning liu on 2018/3/13.
//  Copyright © 2018年 ning liu. All rights reserved.
//

#import "RefreshIconLayer.h"
@interface RefreshIconLayer ()

@property (strong, nonatomic) CAShapeLayer * ringShapeLayer;
@property (strong, nonatomic) UIBezierPath * bezierPath;

@end

@implementation RefreshIconLayer

- (instancetype)init{
    self = [super init];
    if (self) {
        
        [self addSublayer:self.ringShapeLayer];
    }
    return self;
}

- (void)startAnimating{
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    animation.fromValue = @(0.0);
    animation.toValue = @(2*M_PI);
    animation.duration = 0.8;
    animation.repeatCount = INFINITY;
    animation.removedOnCompletion = NO;
    [self.ringShapeLayer addAnimation:animation forKey:animation.keyPath];
}

- (void)stopAnimating{
    self.ringShapeLayer.strokeEnd = 0.0;
    [self.ringShapeLayer removeAllAnimations];
}

- (void)setProgress:(CGFloat)progress{
    self.ringShapeLayer.strokeEnd = progress;
}



- (void)layoutSublayers{
    [super layoutSublayers];
    
    
    self.ringShapeLayer.frame = CGRectMake(0, 0, 44, 44);
    self.ringShapeLayer.position = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
    
    self.bezierPath =[UIBezierPath bezierPathWithRoundedRect:self.ringShapeLayer.bounds cornerRadius:self.ringShapeLayer.frame.size.width/2.];
    
    self.ringShapeLayer.path = self.bezierPath.CGPath;
}


- (CAShapeLayer *)ringShapeLayer{
    if (!_ringShapeLayer) {
        _ringShapeLayer = [CAShapeLayer layer];
        _ringShapeLayer.lineWidth = 3.;
        _ringShapeLayer.backgroundColor = [UIColor clearColor].CGColor;
        _ringShapeLayer.fillColor = [UIColor clearColor].CGColor;
        _ringShapeLayer.strokeColor = [UIColor darkGrayColor].CGColor;
        [_ringShapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithFloat:0.98], [NSNumber numberWithFloat:2.94], nil]];
        _ringShapeLayer.strokeEnd = 0;
    }
    return _ringShapeLayer;
}

@end
